Impementing an Interface

 

Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form:

class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}

If a class implements more than one interface, the interfaces are separated with a comma. The methods that implement an interface must be declared public. Here is a small example class that implements the Callback interface:

class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}

Notice that callback( ) is declared using the public access specifier.

2.3 Accessing Implementations through Interface References :

You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be referred to by such a variable. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them. The calling code can dispatch through an interface without having to know anything about the “callee.”

The following example calls the callback( ) method via an interface reference variable:

class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}

The output of this program is shown here:
callback called with 42

Notice that variable c is declared to be of the interface type Callback, yet it was assigned an
instance of Client. Although c can be used to access the callback( ) method, it cannot access
any other members of the Client class. An interface reference variable only has knowledge
of the methods declared by its interface declaration.

 

JAVA Packages and Interfaces